﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;

namespace TfsAlert.Modules.Header
{
    /// <summary>
    /// Interaction logic for DefaultView.xaml
    /// </summary>
    public partial class DefaultView : UserControl
    {
        private System.Timers.Timer dailyTimer;
        ConfigSettings configSettings;

        public DefaultView()
        {
            InitializeComponent();

            configSettings = new ConfigSettings();
            DataContext = configSettings;

            this.setupTimer();
        }

        private void OnTimedEvent( object source, ElapsedEventArgs e )
        {
            configSettings.ResetData();
            dailyTimer.Interval = getNextInterval().Milliseconds;
        }

        private void setupTimer()
        {
            dailyTimer = new System.Timers.Timer( getNextInterval().TotalMilliseconds);

            // Hook up the Elapsed event for the timer.
            dailyTimer.Elapsed += new ElapsedEventHandler( OnTimedEvent );
            dailyTimer.Enabled = true;

            GC.KeepAlive( dailyTimer );
        }

        internal TimeSpan getNextInterval()
        {
            DateTime scheduledTime = new DateTime(
                DateTime.Now.Year,
                DateTime.Now.Month,
                DateTime.Now.AddDays( 1 ).Day );

            DateTimeOffset dateTimeNow, dateTimeFuture;
            TimeSpan duration;

            dateTimeNow = DateTime.Now;
            dateTimeFuture = scheduledTime;

            duration = dateTimeFuture - dateTimeNow;

            return duration;
        }
    }
}
